<template>
  <MainContainer class="p-5">
    <MyQuery
      v-model:params="params"
      :options="queryOptions"
      @query="handleQuery"
      @reset="handleReset"
    ></MyQuery>
    <div class="flex">
      <el-button type="primary" @click="openDialog()">+添加</el-button>
      <el-button @click="handleBinding()">绑定公众号</el-button>
    </div>
    <MyTable
      v-loading="loading"
      :is-show-selection="false"
      class="my-2"
      :data="list"
      :columns="columns"
    ></MyTable>
    <el-pagination
      v-model:currentPage="params.page"
      v-model:page-size="params.limit"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="justify-end"
      @size-change="handleQuery"
      @current-change="handleQuery"
    />
    <MyFormDialog
      v-model:visible="dialogVisible"
      v-model:formData="formData"
      :title="dialogTitle"
      :options="createFormOptions"
      :loading="loading"
      @confirm="handleConfirm"
    ></MyFormDialog>
    <!-- 绑定微信 -->
    <MyFormDialog
      v-model:visible="wxDialogVisible"
      v-model:formData="wxData"
      title="绑定微信"
      :options="createWxOptions"
      :loading="loading"
      @confirm="handleWxConfirm"
    ></MyFormDialog>
    <!-- 绑定公众号 -->
    <OfficialAccountDialog
      v-model:visible="officialAccountDialogVisible"
      title="绑定公众号"
      @confirm="handleOfficialAccountConfirm"
      @confirm1="handleCompanyConfirm"
    ></OfficialAccountDialog>
    <CompanyDialog
      v-model:visible="companyVisible"
      title="绑定单位"
      :wx-id="wId"
    >
    </CompanyDialog>
    <!-- 分配用户 -->
    <CompanyInformation
      v-model:visible="userListVisible"
      title="单位信息"
      :company-id="userId"
      @confirm="handleUserConfirm"
    ></CompanyInformation>
  </MainContainer>
</template>
<script setup lang="jsx">
import useCRUD from "@/composables/useCRUD.js";
import MyQuery from "@/components/MyQuery.vue";
import MainContainer from "@/components/MainContainer.vue";
import MyFormDialog from "@/components/MyFormDialog.vue";
import MyTable from "@/components/MyTable.vue";
import CompanyInformation from "@/views/admin/company/components/CompanyInformation.vue";
import OfficialAccountDialog from "@/views/admin/company/components/OfficialAccountDialog.vue";
import parseTime from "@/utils/parseTime.js";
import CompanyDialog from "@/views/admin/company/components/CompanyDialog.vue";
import {
  fetchList,
  createCompany,
  deleteCompany,
  updateCompany,
  getCompany,
  getCompanyWxCode,
  checkWxAbnormal,
} from "@/api/robot-company";
import { ref } from "vue";
import robot from "@/assets/images/disinfect/code.jpg";
import { ElMessage, ElMessageBox } from "element-plus";

const queryOptions = [
  {
    prop: "id",
    placeholder: "单位编号",
  },
  {
    prop: "name",
    placeholder: "单位名称",
  },
  {
    prop: "tel",
    placeholder: "单位联系方式",
  },
  {
    prop: "address",
    placeholder: "单位地址",
  },
  {
    prop: "status",
    placeholder: "启用状态",
    customRender() {
      return (
        <el-select placeholder="请选择状态" class="w-full">
          <el-option value={1} label="启用" />
          <el-option value={0} label="禁用" />
        </el-select>
      );
    },
  },
];

const createFormOptions = [
  {
    prop: "name",
    label: "单位名称",
    rules: [
      {
        required: true,
        message: "单位名称不能为空",
        trigger: "blur",
      },
      { min: 2, message: "名称至少须2个字符", trigger: "blur" },
    ],
  },
  {
    prop: "address",
    label: "单位地址",
    rules: [
      {
        required: true,
        message: "单位地址不能为空",
        trigger: "blur",
      },
      { min: 2, message: "单位地址至少须2个字符", trigger: "blur" },
    ],
  },
  {
    prop: "tel",
    label: "联系电话",
    rules: [
      {
        required: true,
        message: "联系电话不能为空",
        trigger: "blur",
      },
      { min: 2, message: "电话至少须2位字符", trigger: "blur" },
    ],
  },
  {
    prop: "remark",
    label: "备注",
  },
  {
    prop: "status",
    label: "是否启用",
    required: true,
    rules: {
      required: true,
      message: "必填",
    },
    customRender() {
      return (
        <el-radio-group>
          <el-radio label={1}>是</el-radio>
          <el-radio label={0}>否</el-radio>
        </el-radio-group>
      );
    },
  },
];

const columns = [
  {
    prop: "id",
    label: "编号",
  },
  {
    prop: "name",
    label: "单位名称",
  },
  {
    prop: "tel",
    label: "联系电话",
  },
  {
    prop: "address",
    label: "单位地址",
  },
  {
    prop: "remark",
    label: "备注",
  },
  {
    label: "是否启用",
    prop: "status",
    customRender(row) {
      return (
        <el-switch
          v-model={row.status}
          active-value={1}
          inactive-value={0}
          onChange={() => handleUpdate(row.id, row)}
        ></el-switch>
      );
    },
  },
  {
    prop: "createTime",
    label: "创建时间",
    formatter(row) {
      const date = new Date(row.createTime);
      return parseTime(date);
    },
  },
  {
    prop: "updateTime",
    label: "修改时间",
    formatter(row) {
      const date = new Date(row.updateTime);
      return parseTime(date);
    },
  },
  {
    prop: "updateUname",
    label: "修改人",
  },
  {
    label: "操作",
    prop: "action",
    minWidth: 100,
    customRender(row) {
      return (
        <div>
          <el-button
            class="!text-[#707bdf]"
            link
            onClick={() => openWxDialog(row.id)}
          >
            绑定微信
          </el-button>
          <el-button
            class="!text-[#707bdf]"
            link
            onClick={() => openUserList(row.id)}
          >
            分配用户
          </el-button>
          <el-button
            link
            type="danger"
            onClick={async () => {
              await ElMessageBox.confirm("确认继续操作吗", "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
              });
              const { message } = await handleDelete(row.id);
              ElMessage({ type: "success", message });
            }}
          >
            删除
          </el-button>
          <el-button
            class="!text-[#707bdf]"
            link
            onClick={() => openDialog(row.id)}
          >
            编辑
          </el-button>
        </div>
      );
    },
  },
];

const officialAccountDialogVisible = ref(false);
const companyVisible = ref(false);
//绑定公众号
async function handleBinding() {
  officialAccountDialogVisible.value = true;
}
const wId = ref(0);
function handleOfficialAccountConfirm(id) {
  wId.value = id;
}

function handleCompanyConfirm(v) {
  companyVisible.value = v;
}

const crudOptions = {
  queryApi: fetchList,
  createApi: createCompany,
  deleteApi: deleteCompany,
  updateApi: updateCompany,
  getOneApi: getCompany,
};
const {
  params,
  handleQuery,
  list,
  loading,
  handleReset,
  openDialog,
  dialogVisible,
  handleDelete,
  formData,
  dialogTitle,
  total,
  handleConfirm,
  handleUpdate,
} = useCRUD(crudOptions);

handleQuery();

// 绑定微信相关
const createWxOptions = [
  {
    prop: "name",
    label: "微信绑定码",
    customRender() {
      return (
        <div class="flex flex-1 items-center">
          <el-input
            disabled
            class="h-full"
            v-model={wxData.value.name}
          ></el-input>
          <el-image class=" select-none right" src={robot} />
        </div>
      );
    },
  },
  {
    prop: "rename",
    label: "绑定标识",
    rules: [
      {
        required: true,
        message: "标识不能为空",
        trigger: "blur",
      },
    ],
  },
  {
    prop: "remark",
    label: "备注",
  },
];

const wxDialogVisible = ref(false);
const wxId = ref(null);
const wxData = ref({});

function openWxDialog(id) {
  wxId.value = id;
  wxDialogVisible.value = true;
  getRoleByWx(id);
}

async function getRoleByWx(id) {
  const res = await getCompanyWxCode(id);
  wxData.value.name = res.data.name;
}

async function handleWxConfirm(data) {
  ElMessageBox.confirm("确认继续操作吗", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      checkWxAbnormal(wxId.value, data.rename);
      ElMessage({
        type: "success",
        message: "已绑定",
      });
      wxDialogVisible.value = false;
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
      wxDialogVisible.value = true;
    });
}

const userListVisible = ref(false);
const userId = ref(null);

function openUserList(id) {
  userId.value = id;
  userListVisible.value = true;
}

async function handleUserConfirm() {
  userListVisible.value = false;
}
</script>
